package com.knowno.customer;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;


import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import java.io.IOException;
import java.util.List;

import org.jetbrains.annotations.NotNull;

/**
 *XfSparkWebSocketListener
 */
public class XfSparkWebSocketListener extends WebSocketListener {
    public StringBuilder answer = new StringBuilder();

    public boolean wsCloseFlag = false;
    public static final Gson gson = new Gson();

    @Override
    public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
        super.onOpen(webSocket, response);
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            // 日志记录
            this.answer = new StringBuilder("大模型响应错误，请稍后再试");
            wsCloseFlag = true;
            return;
        }
        // 将回答进行拼接
        List<JsonParse.Text> textList = myJsonParse.payload.choices.text;
        for (JsonParse.Text temp : textList) {
            System.out.println("temp :"+temp.content);
            this.answer.append(temp.content);
        }
        // 对最后一个文本结果进行处理
        if (myJsonParse.header.status == 2) {
            wsCloseFlag = true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Override
    public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosed(webSocket, code, reason);
    }
}
